// packageMyInfo/pages/person/person.js
const app = getApp()
let phoneReg = /^[1][0-9]{10}$/
import { throttle } from "../../../utils/util"
import { deviceFindAll,userBindDevice } from "../../../public/api/device.js"
import { userInsert } from "../../../public/api/person.js"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    translations: {},
    language: '',
    deviceList: [],
    device: {},
    hideModal: true,
    phone: '',
    checkList: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  getDeviceList() {
    let that = this
    let data = {}
    data.uuid = ''
    deviceFindAll(data).then(res => {
      if(res.data.code === 1) {
        res.data.data.map(item => {
          item.uuidShow = that.formatString(item.uuid)
          item.disabled = item.userType == 0 ? false : true
        })
        this.setData({deviceList: res.data.data})
      } else {
        wx.showToast({
          title: res.data.msg,
          icon: 'none'
        })
      }
    })
  },

  formatString(str) {
    if (str.length <= 8) {
      // 如果字符串长度小于或等于8，直接返回原字符串
      return str;
    }
    const start = str.slice(0, 4); // 获取前4位
    const end = str.slice(-4); // 获取后4位
    return `${start}****${end}`; // 用****替换中间部分
  },

  showUuid: throttle(function(e) {
    let uuid = e.currentTarget.dataset.uuid
    wx.showModal({
      title: '',
      content: uuid,
      confirmText: '复制',
      success: (res) => {
        if(res.confirm) {
          wx.setClipboardData({
            data: uuid,
            success: function (res) {
              wx.showToast({
                title: '复制成功',
                icon: 'none'
              });
            }
          });
        }
      }
    })
  },1500),

  goPersonSub(e) {
    let { uuid, name } = e.currentTarget.dataset
    wx.navigateTo({
      url: '../personSub/personSub?uuid=' + uuid + '&name=' + name
    })
  },

  openModal() {
    if(JSON.stringify(this.data.device) == '{}') {
      wx.showToast({
        title: '请先选择设备',
        icon: 'none'
      })
    } else {
      this.setData({hideModal: false})
    }
  },

  checkboxChange(e) {
    console.log(e);
    let that = this
    let uuid = e.currentTarget.dataset.uuid
    let device = this.data.device
    let deviceList = [].concat(...this.data.deviceList)
    if(device[uuid]) {
      delete device[uuid]
    } else {
      device[uuid] = deviceList.find(v => v.uuid === uuid)
    }
    console.log(device);
    this.setData({device})
  },

  doAdd: throttle(function() {
    let that = this
    if(that.data.phone === '') {
      wx.showToast({
        title: that.data.translations.person.enter_authorized_by_wechat,
        icon: 'none'
      })
      return false
    }
    if(!phoneReg.test(this.data.phone)) {
      wx.showToast({
        title: '手机号格式不正确',
        icon: 'none'
      })
      return false
    }
    let data = {}
    data.phone = that.data.phone
    data.uuids = Object.values(that.data.device).map(item => item.uuid)
    userBindDevice(data).then(res => {
      if(res.data.code === 1) {
        wx.showToast({
          title: '添加成功',
          icon: 'success'
        })
        that.getDeviceList()
        that.setData({
          hideModal: true,
          phone: ''
        })
      } else {
        wx.showToast({
          title: res.data.msg,
          icon: 'none'
        })
      }
    })
  }),

  doCancel() {
    this.setData({
      hideModal: true,
      phone: ''
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let language = wx.getStorageSync('language')
    const translations = app.globalData.translations;
    this.setData({
      language,
      translations
    })
    wx.setNavigationBarTitle({
      title: translations.nav.personnel_management
    });
    this.getDeviceList()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})